package com.niit.chat.controller;

import com.niit.chat.entity.Message;
import com.niit.chat.service.MessageService;
import com.niit.chat.common.Result;
import com.niit.chat.utils.QiniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息控制器
 * 处理消息相关的HTTP请求
 */
@RestController
@RequestMapping("/api/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private QiniuUtil qiniuUtil;

    /**
     * 发送消息
     * 
     * @param message 消息对象
     * @return 发送结果
     */
    @PostMapping("/send")
    public Result<Message> sendMessage(@RequestBody Message message) {
        boolean success = messageService.sendMessage(message);
        if (success) {
            return Result.success(message); // 返回完整的消息对象
        } else {
            return Result.error("发送失败");
        }
    }

    /**
     * 获取与指定用户的聊天历史记录
     * 
     * @param userId 当前用户ID
     * @param targetUserId 目标用户ID
     * @param page 页码，默认1
     * @param size 每页大小，默认20
     * @return 消息列表
     */
    @GetMapping("/history/{userId}/{targetUserId}")
    public Result<List<Message>> getChatHistory(
            @PathVariable Long userId,
            @PathVariable Long targetUserId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        return Result.success(messageService.getChatHistory(userId, targetUserId, page, size));
    }

    /**
     * 获取用户的未读消息数量
     * 
     * @param userId 用户ID
     * @return 未读消息数量
     */
    @GetMapping("/unread/{userId}")
    public Result<Integer> getUnreadCount(@PathVariable Long userId) {
        return Result.success(messageService.getUnreadCount(userId));
    }

    /**
     * 将指定消息标记为已读
     * 
     * @param messageIds 需要标记为已读的消息ID列表
     * @return 标记结果
     */
    @PostMapping("/read")
    public Result<Boolean> markAsRead(@RequestBody List<Long> messageIds) {
        return Result.success(messageService.markAsRead(messageIds));
    }

    /**
     * 撤回消息（2分钟内）
     */
    @PostMapping("/recall/{messageId}/{userId}")
    public Result<Boolean> recallMessage(@PathVariable Long messageId, @PathVariable Long userId) {
        return messageService.recallMessage(messageId, userId);
    }

    /**
     * 删除消息（单方删除）
     */
    @PostMapping("/delete/{messageId}/{userId}")
    public Result<Boolean> deleteMessage(@PathVariable Long messageId, @PathVariable Long userId) {
        return Result.success(messageService.deleteMessage(messageId, userId));
    }

    @PostMapping("/upload")
    public Result<List<String>> uploadMedia(@RequestParam("files") MultipartFile[] files) {
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file.isEmpty()) continue;
            try (InputStream in = file.getInputStream()) {
                String url = qiniuUtil.uploadFile(in, file.getOriginalFilename());
                urls.add(url);
            } catch (Exception e) {
                e.printStackTrace();
                return Result.error("文件上传失败: " + e.getMessage());
            }
        }
        return Result.success(urls);
    }
} 